//
//  FoodDetailViewController.m
//  Funny
//
//  Created by dllo on 15/11/2.
//  Copyright © 2015年 King. All rights reserved.
//

#import "FoodDetailViewController.h"

@interface FoodDetailViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *contentV;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSDictionary *dic;
@property (nonatomic, strong) UIImageView *imgView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *text1;
@property (nonatomic, strong) UILabel *textAdd;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) DataBase *dataBase;
@property (nonatomic, strong) NSArray *dbArr;
@property (nonatomic, assign) BOOL isOpen;
@property (nonatomic, strong) MBProgressHUD *hub;
@property (nonatomic, strong) FoodInfoModel *model;

@end

@implementation FoodDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     [self handle];

    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    [self.view addSubview:self.scrollView];
    self.scrollView.showsVerticalScrollIndicator = NO;
    [self.scrollView addSubview:self.titleLabel];
    [self.scrollView addSubview:self.text1];
    [self.scrollView addSubview:self.textAdd];
    [self.scrollView addSubview:self.tableView];
    UIButton *backClick = [UIButton buttonWithFrame:CGRectMake(0, 23, 60, 30) color:nil title:@" 返回" type:UIButtonTypeSystem target:nil action:@selector(backToPage) event:UIControlEventTouchUpInside cornerRadius:0];
    backClick.tintColor = [UIColor whiteColor];
    [backClick setImage:[UIImage imageNamed:@"btn_back@3x.png"] forState:UIControlStateNormal];
    UIImageView *backImg= [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 64)];
    
    backImg.image = [UIImage imageNamed:@"back1.png"];
    [self.view addSubview:backImg];
    [self.view addSubview:backClick];
    
    // 收藏按钮
    UIButton *collectClick = [UIButton buttonWithFrame:CGRectMake(ScreenWidth - 50, 23, 35, 35) color:nil title:nil type:UIButtonTypeSystem target:self action:@selector(collectClickWithBtn:) event:UIControlEventTouchUpInside cornerRadius:0];
    [self.view addSubview:collectClick];
    
    // 进入页面时首先判断是否已收藏 已收藏显示红色 否则白色
    BOOL result = [self.dataBase open];
    if (result) {
        [self.dataBase creatInlandTable];
    }
    self.dbArr = [self.dataBase getInlandAll];
    if (_dbArr.count == 0) {
        [collectClick setImage:[UIImage imageNamed:@"nocollect.png"] forState:UIControlStateNormal];
        collectClick.tintColor = [UIColor whiteColor];
        _isOpen = NO;
    }
    for (FoodInfoModel *model in _dbArr) {
        
        if ([model.cityID integerValue] == [self.ID integerValue]) {
            [collectClick setImage:[UIImage imageNamed:@"collected.png"] forState:UIControlStateNormal];
            [collectClick setTintColor:[UIColor redColor]];
            _isOpen = YES;
            break;
        }
        else{
            [collectClick setImage:[UIImage imageNamed:@"nocollect.png"] forState:UIControlStateNormal];
            collectClick.tintColor = [UIColor whiteColor];
            _isOpen = NO;
        }
    }
}

- (NSArray *)dbArr{
    if (!_dbArr) {
        self.dbArr = [NSArray array];
    }
    return _dbArr;
}

// 数据库初始化 懒加载
- (DataBase *)dataBase
{
    if (!_dataBase) {
        self.dataBase = [DataBase shareDataBase];
    }
    return _dataBase;
}

#pragma mark - 数据库增减
- (void)collectClickWithBtn:(UIButton *)btn
{
    self.hub = [[MBProgressHUD alloc]initWithView:self.view];
    if (_isOpen == YES) {
        [self.dataBase deleteInlandDataWithModel:_model];
        [btn setImage:[UIImage imageNamed:@"nocollect.png"] forState:UIControlStateNormal];
        btn.tintColor = [UIColor whiteColor];
        _hub.labelText = @"删除成功";
        _isOpen = NO;
    }else
    {
        if (_model.cityID == nil) {
            _hub.labelText = @"未加载完成哦";
        }
        else{
            [self.dataBase insertInlandDataWithModel:_model];
            [btn setImage:[UIImage imageNamed:@"collected.png"] forState:UIControlStateNormal];
            btn.tintColor = [UIColor redColor];
            _hub.labelText = @"收藏成功";
            _isOpen = YES;
        }
    }
    [self.view addSubview:_hub];
    [_hub showAnimated:NO whileExecutingBlock:^{
        sleep(1);
    } completionBlock:^{
        [_hub removeFromSuperview];
    }];
}


- (void)handle
{
    NSString *URLstr = [NSString stringWithFormat:@"http://open.qyer.com/qyer/footprint/poi_detail?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&lat=38.88270678796906&lon=121.539278349696&page=1&poi_id=%@&screensize=750&track_app_channel=App Store&track_app_version=6.8&track_device_info=iPhone7,2&track_deviceid=357AAE6A-2231-4843-84E7-0ED164F35BDD&track_os=ios 9.0.2&v=1",self.ID];
    [HandleData handleDataWithUrl:URLstr completion:^(id data) {
        NSDictionary *dic = data;
        self.dic = [dic objectForKey:@"data"];
        [self.imgView sd_setImageWithURL:[NSURL URLWithString:[self.dic objectForKey:@"photo"]] placeholderImage:[UIImage imageNamed:@"chartlet_image_traning.png"]];
        self.titleLabel.text = [self.dic objectForKey:@"firstname"];
        self.text1.text = [self.dic objectForKey:@"introduction"];
        [self setLineSpacing:12 label:self.text1];
        NSArray *arr = [[self.dic objectForKey:@"comment_list"] objectForKey:@"othercomment"];
        for (NSDictionary *dataDic in arr) {
            FoodDetailModel *model = [FoodDetailModel modelWithDic:dataDic];
            [self.dataArr addObject:model];
        }
        
        self.model = [[FoodInfoModel alloc]init];
        self.model.pic = [self.dic objectForKey:@"photo"];
        self.model.content = [self.dic objectForKey:@"introduction"];
        self.model.cityID = self.ID;
        
        [self.tableView reloadData];
        WeakSelf(weakSelf);
        CGRect rect1 = [self.text1.text boundingRectWithSize:CGSizeMake(335*W, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19]} context:nil];
        [self.text1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakSelf.titleLabel.mas_bottom).offset(30);
            make.left.equalTo(weakSelf.view).offset(20);
            make.size.mas_equalTo(CGSizeMake(335*W, rect1.size.height));
        }];
        if ([[self.dic objectForKey:@"address"] isEqual:[NSNull null]]) {
            self.textAdd.text = @"暂无信息";
        }else
        {
            self.textAdd.text = [self.dic objectForKey:@"address"];
        }
        [self setLineSpacing:12 label:self.textAdd];

        CGRect rect2 = [self.textAdd.text boundingRectWithSize:CGSizeMake(335*W, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19]} context:nil];
        [self.textAdd mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakSelf.text1.mas_bottom).with.offset(50);
            make.left.equalTo(weakSelf.view).offset(20);
            make.size.mas_equalTo(CGSizeMake(335*W, rect2.size.height));
        }];
        [_tableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakSelf.textAdd.mas_bottom).with.offset(20);
            make.left.equalTo(weakSelf.view);
            make.size.mas_equalTo(CGSizeMake(ScreenWidth, ScreenHeight));
        }];
        self.scrollView.contentSize = CGSizeMake(0, rect1.size.height + rect2.size.height + 350 + 250);
    }];
}

- (void)backToPage
{
    [self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (UIImageView *)imgView
{
    if (!_imgView) {
        _imgView = [[UIImageView alloc]init];
        [self.scrollView addSubview:_imgView];
        _imgView.frame = CGRectMake(0, -20*H, self.view.bounds.size.width, 190*H);
    }
    return _imgView;
}

- (UILabel *)titleLabel
{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc]init];
        _titleLabel.font = [UIFont systemFontOfSize:18];
        _titleLabel.frame = CGRectMake(20*W, 187*H, 300*W, 20*H);
    }
    return _titleLabel;
}

- (UILabel *)text1
{
    if (!_text1) {
        _text1 = [[UILabel alloc]init];
        _text1.numberOfLines = 0;
        _text1.font = [UIFont systemFontOfSize:14];
        _text1.lineBreakMode = NSLineBreakByCharWrapping;
        UILabel *label = [[UILabel alloc]init];
        label.text = @"简介";
        [self.scrollView addSubview:label];
        WeakSelf(weakSelf);
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakSelf.titleLabel.mas_bottom).with.offset(10);
            make.size.mas_equalTo(CGSizeMake(80*W, 20*H));
            make.left.equalTo(weakSelf.scrollView).with.offset(20);
        }];
    }
    return _text1;
}
- (UILabel *)textAdd
{
    if (!_textAdd) {
        _textAdd = [[UILabel alloc]init];
        _textAdd.numberOfLines = 0;
        _textAdd.font = [UIFont systemFontOfSize:14];
        _textAdd.lineBreakMode = NSLineBreakByCharWrapping;
        UILabel *label = [[UILabel alloc]init];
        label.text = @"地址";
        [self.scrollView addSubview:label];
        WeakSelf(weakSelf);
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(weakSelf.text1.mas_bottom).with.offset(10);
            make.size.mas_equalTo(CGSizeMake(80*W, 20*H));
            make.left.mas_equalTo(weakSelf.scrollView).with.offset(20);
        }];
    }
    return _textAdd;
}

- (NSMutableArray *)dataArr
{
    if (!_dataArr) {
        self.dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[FoodDetailTableViewCell class] forCellReuseIdentifier:@"reuse"];

    }
    return _tableView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FoodDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    cell.model = _dataArr[indexPath.row];
    return cell;
}

- (void)setLineSpacing:(CGFloat)spacing label:(UILabel *)label
{
    NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:label.text];
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:spacing];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [label.text length])];
    [label setAttributedText:attributedString];
    [label sizeToFit];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [self.dataBase close];
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.dataBase open];
    self.dbArr = [self.dataBase getInlandAll];
    self.navigationController.navigationBarHidden = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
